<?php

/*
Select Meta Image - included in the Kiwi release.
Download the stand-alone plugin at http://no.oneslistening.com
*/

add_action('edit_form_advanced', 'select_meta_image');
add_action('save_post','save_meta_image');
add_action('edit_post','save_meta_image');
add_action('publish_post','save_meta_image');

function select_meta_image() {
	global $post_ID;
	
	$dir = '../wp-content/themes/kiwicanvas/metapics/'; // This path is referenced from the wp-admin directory, where the plugin is called
	
	if (substr($dir,-1) != '/') {
		$dir = $dir.'/';
	}

	$files = scandirectory($dir); // Scans the directory for files

	// The Javascript (not my forte) that changes the look of the selected image
	echo "<script language=\"JavaScript\">
function changeStyleById(id,color,border,padding){
if (document.getElementById)
   {
   var nodeObj = document.getElementById(id)
   nodeObj.style.backgroundColor = color;
   nodeObj.style.border = border;
   nodeObj.style.padding = padding;
   }
}
function changeStyleByTag(tag,color,border,padding){
if(document.getElementsByTagName)
   {
   var nodes = document.getElementsByTagName(tag)
   var max = nodes.length
   for(var i = 0;i < max;i++)
      {
      var nodeObj = nodes.item(i);
      nodeObj.style.backgroundColor = color;
      nodeObj.style.border = border;
      nodeObj.style.padding = padding;
      }
   }
}
function domSwap(id,src){
	theImg=document.getElementById(id);
	theImg.setAttribute(\"src\",src);
}
</script>";
	echo '<h2>Preview Image</h2>'; 
	
	$meta_form_value = 'the_meta_image';
	$site_uri = get_settings('siteurl'); // your site URI, the image paths are appended to this
	if (substr($site_uri,-1) != '/') {
		$site_uri = $site_uri.'/';
	}
	
	// The following code will display the currently set meta image, if it exists
	// and assigns variables to tell save_meta_image the ID and current image status
	if(has_meta($post_ID)) {
		$meta_prepic = has_meta($post_ID);
		
		// Finds the appropriate metadata and displays an image if it's already set.
		foreach ($meta_prepic as $entry) {
			if($entry['meta_key'] == 'prepic') {
				echo '<input type="hidden" id="meta_image_ID" name="meta_image_ID" value="'.$entry['meta_id'].'" />';
				echo '<strong>The currently assigned preview picture</strong> (does not reflect any changes made below)<br>';
				$image = '<img id="prepic0" src="'.$site_uri.$entry['meta_value'].'" alt="Preview Image"/>';
				$status = 1;
			} 
		}
		if($status != 1) $image = '<img id="prepic0" src="../wp-content/themes/kiwi/kiwi-images/noimage.gif" alt="Preview Image" style="padding:3px; margin:5px; border:1px solid #ccc;" />';
	} else {
		$image = '<img id="prepic0" src="../wp-content/themes/kiwi/kiwi-images/noimage.gif" alt="Preview Image" style="padding:3px; margin:5px; border:1px solid #ccc;" />';
	}
	echo $image;	
	
	echo '<h3>Click on the image you\'d like to use as a preview:</h3>These are pre-existing pictures you may find helpful <span style="font-size:8px">(contents from the directory path: <code>'.$dir.'</code>)</span><br>';
	
	echo '<div style="width: 625px; height: 200px; overflow: scroll; border: 1px solid #000; padding: 10px;">';

	echo '<h5>The Meta Image All-Stars</h5>';
	// This loop displays the contents of the directory (only jpg and gif, but you could change that below)
	// and creates the links necessary to call the Javascript
	//
	// Where you see the 'onclick' call is where the value is added. If you're having problems with your images
	// not showing up, sometimes fiddling with the number in the 'substr' function can solve it
	$i=1;
	foreach($files as $file) {
		if(substr($file, -3) == 'jpg' OR substr($file, -3) == 'gif') {
			echo '<a href="javascript:void(0);" onclick="domSwap(\'prepic0\', \''.$dir.$file.'\'),document.post.'.$meta_form_value.'.value=\''.substr($dir,3).$file.'\', changeStyleByTag(\'img\',\'#fff\',\'1px solid #ccc\',\'3px\'), changeStyleById(\'prepic'.$i.'\',\'#C3DAEA\',\'2px solid #000\',\'2px\')"><img id="prepic'.$i.'" style="width:23%; height:auto; padding:3px; margin:5px; border:1px solid #ccc;" onmouseover="changeStyleById(\'prepic'.$i.'\',\'#C3DAEA\')" onmouseout="changeStyleById(\'prepic'.$i.'\',\'#fff\')" src="'.$dir.$file.'" /></a>';
		$i++;
		}
	}
	
	echo '</div>';
	
	echo '<input type="hidden" name="the_meta_image" id="the_meta_image" size="40" value="null" /><br/><div id="imagePath"> &nbsp;</div>';

}

// This function saves the data passed to it when the post is saved or published.
function save_meta_image($post_ID) {
	global $wpdb;
	
	$metakey = 'prepic';
	$metavalue = $_POST['the_meta_image'];
	$meta_image_ID = $_POST['meta_image_ID'];

	if($_POST['the_meta_image'] != 'null') {
		if(!$wpdb->query("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_ID' AND meta_key = 'prepic'")) {
			$result = $wpdb->query("
				INSERT INTO $wpdb->postmeta 
				(post_id,meta_key,meta_value) 
				VALUES ('$post_ID','$metakey','$metavalue')
			");

			return $result;

		} elseif($wpdb->query("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_ID' AND meta_key = 'prepic'")) {		
			$result = $wpdb->query("
				UPDATE $wpdb->postmeta 
				SET meta_value = '$metavalue' 
				WHERE meta_id = '$meta_image_ID'
			");

			return $result;		
		}
	}
}

// Use this function to display the image in your php file (within the Wordpress Loop)
// Output is the <img> as a link to the associated post.
function the_meta_image() {	
	$metadata = get_post_custom_values($key='prepic');
	if(isset($metadata)) {
		$string =  '<a href="'.get_permalink().'"><img class="metaimage" src="'.get_option('siteurl').'/'. $metadata[0].'" alt="Preview Image"/></a>';
		echo $string;
	}
}

// Scans the directory, included for PHP 4 users
if(!function_exists(scandirectory)) {
	function scandirectory($dir = './', $sort = 0) {
	  
		$dir_open = @opendir($dir);
	
		if (!$dir_open) {
			return false;
		}
	
		while (($dir_content = readdir($dir_open)) !== false) {
			$files[] = $dir_content;
		}
	
		if ($sort == 1) { 
			rsort($files, SORT_STRING);
		} else {
			sort($files, SORT_STRING);
		}
	
		return $files;
	}
}
?>